package kz.vokebuz;

/*
 * Copyright (C) 2010 Deez Apps!
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import kz.vokebuz.dataStore.DataService;
import kz.vokebuz.dataStore.DbAdapter;
import kz.vokebuz.dataStore.SmsMmsMsg;
import kz.vokebuz.dataStore.SmsSimplCursorAdapter;
import kz.vokebuz.dataStore.WellcomCursorAdapter;
import kz.vokebuz.scrool.HorizontalPager;
import kz.vokebuz.scrool.PagerControl;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();

	private ListView listView;
	private ListView wellcomeList;
	private DbAdapter dbAdapter;
	private IntentFilter filter = new IntentFilter();
	private HorizontalPager pager;
	private SmsSimplCursorAdapter smsRows;
	private WellcomCursorAdapter wellcomRows;
    private Cursor cursorSms;
    private Cursor cursor;
	@Override
	protected void onPause() {
		unregisterReceiver(receiver);
		super.onPause();
	}

	@Override
	protected void onResume() {

		filter.addAction(DataService.BROADCAST);
		registerReceiver(receiver, filter);
		fillWellcomList();
		super.onResume();
	}

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		filter.addAction(DataService.BROADCAST);
		registerReceiver(receiver, filter);
		dbAdapter = new DbAdapter(this);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final PagerControl control = (PagerControl) findViewById(R.id.control);
		pager = (HorizontalPager) findViewById(R.id.pager);

		wellcomeList = (ListView) findViewById(R.id.listWellcome);
		listView = (ListView) findViewById(R.id.listSms);
		wellcomeList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.d(TAG, "click event");
				Cursor c = (Cursor) wellcomeList.getItemAtPosition(position);
				c.getString(c.getColumnIndex("categoryid"));
				processClick(c.getString(c.getColumnIndex("categoryid")));

			}

		});

		fillWellcomList();
		// fillList();

		control.setNumPages(pager.getChildCount());

		pager.addOnScrollListener(new HorizontalPager.OnScrollListener() {
			public void onScroll(int scrollX) {
				// Log.d("TestActivity", "scrollX=" + scrollX);
				float scale = (float) (pager.getPageWidth() * pager
						.getChildCount()) / (float) control.getWidth();
				control.setPosition((int) (scrollX / scale));
			}

			public void onViewScrollFinished(int currentPage) {
				// Log.d("TestActivity", "viewIndex=" + currentPage);
				control.setCurrentPage(currentPage);
			}
		});

	}

	private void fillWellcomList() {
		dbAdapter.open();
		cursor = dbAdapter.getWellcomeListItems();
		startManagingCursor(cursor);
		// cursor.moveToFirst();
		String[] from = new String[] { "categoryid", "isread" };

		int[] to = new int[] { R.id.rowWelcName, R.id.rowWelcName };
		wellcomRows = new WellcomCursorAdapter(this,
				R.layout.wellcomerow, cursor, from, to);
		wellcomeList.setAdapter(wellcomRows);
		dbAdapter.close();

	}

	private void fillList() {
		dbAdapter.open();
		cursorSms = dbAdapter.getAllSms();
		startManagingCursor(cursorSms);
		String[] from = new String[] { SmsMmsMsg.COLUMN_SENDER,
				SmsMmsMsg.COLUMN_TEXT };

		int[] to = new int[] { R.id.rowSender, R.id.rowText };
		smsRows = new SmsSimplCursorAdapter(this,
				R.layout.listrow, cursorSms, from, to);
		listView.setAdapter(smsRows);
		listView.setLayoutParams(new RelativeLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		dbAdapter.close();
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.d(TAG, "requery list");
			fillList();

		}
	};

	private void processClick(String str) {
		Log.d(TAG, "process Click event");
		if (str.equals("inbox")) {
			fillList();
			pager.scrollRight();
		} else if (str.equals("new_folder")) {
			Uri uriSMSURI = Uri.parse("content://sms/");
			Cursor cur = getApplicationContext().getContentResolver().query(
					uriSMSURI, null, null, null, null);
			StringBuffer info = new StringBuffer();
			for (int i = 0; i < cur.getColumnCount(); i++) {
				info.append("Column: " + cur.getColumnName(i) + "\n");
			}
			Log.d(TAG, info.toString());
		}
		// Toast.LENGTH_LONG).show();

	}


	@Override
	protected void onStop() {
		try {
			super.onStop();
			if (this.cursor!= null){
				this.cursor.close();
			}
			if (this.cursorSms!=null){
				this.cursorSms.close();
			}
		} catch (Exception error) {
			/** Error Handler Code **/
		}
	}

}
